<template>
  <div>
    <el-drawer
      class="master-drawer"
      v-model="open"
      :title="formData?.billNumber"
      size="1300px"
      @close="closeDrawer"
      destroy-on-close
    >
      <div class="drawer-wrap" v-loading="loading">
        <div class="drawer-wrap-left" ref="scrollContainer">
          <el-form ref="submitFormRef" :model="formData" :rules="rules" label-width="auto">
            <div class="left-title">工单基本信息</div>
            <el-descriptions :column="2">
              <el-descriptions-item label="单据编号："
                >{{ formData?.billNumber }}
              </el-descriptions-item>
              <el-descriptions-item label="单据类型："
                >{{ formData?.billType }}
              </el-descriptions-item>
              <el-descriptions-item label="单据日期："
                >{{ formData?.documentTime }}
              </el-descriptions-item>
              <el-descriptions-item label="拆分状态："
                >{{ formData?.splitStatus }}
              </el-descriptions-item>
              <el-descriptions-item label="物料编码："
                >{{ formData?.materialCode }}
              </el-descriptions-item>
              <el-descriptions-item label="物料名称：">
                <el-tooltip
                  effect="dark"
                  :content="formData?.materialName"
                  placement="bottom-start"
                >
                  <div class="ellipsis">{{ formData?.materialName }}</div>
                </el-tooltip>
              </el-descriptions-item>
              <el-descriptions-item label="规格型号：">
                <el-tooltip
                  effect="dark"
                  :content="formData?.specificationType"
                  placement="top-start"
                >
                  <div class="ellipsis">{{ formData?.specificationType || '-' }}</div>
                </el-tooltip>
              </el-descriptions-item>
              <el-descriptions-item label="单位：">{{ formData?.unit }}</el-descriptions-item>
              <el-descriptions-item label="业务状态：" span="1"
                >{{ formData?.businessStatus }}
              </el-descriptions-item>
              <el-descriptions-item label="齐套日期：" span="1">
                {{ formData?.completionTime }}
              </el-descriptions-item>
              <el-descriptions-item label="拆分数量：" span="1">
                {{ formData?.splitAmount || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="外购线材交期：" span="2">
                {{ formData?.outsourceStartTime }}-{{ formData?.outsourceEndTime }}
              </el-descriptions-item>
            </el-descriptions>
            <div class="left-title">工艺选择</div>
            <div>
              <el-checkbox
                v-model="item.checked"
                :label="item.processName"
                v-for="(item, index) in formData.selectedProcessOrder"
                :key="index"
                @change="handleSelectedProcessOrder(item)"
              />
            </div>
            <div class="table-container">
              <el-table
                row-key="uuid"
                :data="selectedProcessOrder"
                default-expand-all
                height="100%"
                :tree-props="{ children: 'assignedWorkOrders' }"
              >
                <el-table-column
                  prop="processName"
                  label="工艺"
                  align="center"
                  width="140"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="showBillNumber"
                  label="工单"
                  align="center"
                  width="140"
                  show-overflow-tooltip
                >
                  <template #default="scoped">{{ scoped.row.showBillNumber }}</template>
                </el-table-column>
                <el-table-column prop="projectCaseMo" label="时间周期" align="center" width="240">
                  <template #default="scoped">
                    <dc-date-range-picker
                      v-if="!scoped.row.isChild"
                      v-model:startDate="scoped.row.startTime"
                      v-model:endDate="scoped.row.endTime"
                      :earliestDate="lastTime"
                      @change="handleDateChange($event, scoped.row)"
                      :clearable="true"
                    />
                    <span v-else
                      >{{ scoped.row.startTime || '-' }}至{{ scoped.row.endTime || '-' }}</span
                    >
                  </template>
                </el-table-column>
                <el-table-column label="单件标工" align="center" width="160">
                  <template #default="scoped">
                    <el-input-number
                      class="processing-time"
                      v-model="scoped.row.processingTime"
                      controls-position="right"
                      :min="0"
                      :precision="3"
                      v-if="scoped.row.isChild"
                    >
                      <template #suffix>
                        <span>小时</span>
                      </template>
                      <template #decrease-icon>
                        <el-icon>
                          <Minus />
                        </el-icon>
                      </template>
                      <template #increase-icon>
                        <el-icon>
                          <Plus />
                        </el-icon>
                      </template>
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="billNumber" label="小组" align="center" width="140">
                  <template #default="scoped">
                    <el-select
                      v-model="scoped.row.workGroupCode"
                      placeholder="请选择"
                      @change="handleGroupChange(scoped.row)"
                      v-if="!scoped.row.isChild"
                    >
                      <el-option
                        v-for="item in scoped.row.workGroups"
                        :key="item.workGroupCode"
                        :label="item.workGroupName"
                        :value="item.workGroupCode"
                      />
                    </el-select>
                    <span v-else>{{ scoped.row.workGroupName || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" align="center" width="140">
                  <template #default="scoped">
                    <el-button text v-if="scoped.row.canAdd" @click="addChildren(scoped.row)">
                      添加工单
                    </el-button>
                    <el-button text v-if="!scoped.row.isVirtual" @click="removeRow(scoped.row)">
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form>
        </div>
        <div class="drawer-wrap-right">
          <div class="wrap-title">未分配工单</div>
          <ul class="unselect-list">
            <li
              class="list-item"
              v-for="(item, index) in formData.unallocatedWorkOrder"
              :key="index"
            >
              <span class="ellipsis">
                {{ item.showBillNumber }}
              </span>
            </li>
          </ul>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleVerify">提交</el-button>
          <el-button @click="closeDrawer">取消</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 工单数据校验弹 -->
    <el-dialog v-model="openVerify" destroy-on-close @close="closeVerify">
      <template #header>
        <div class="warn-text">请仔细核对工单数据</div>
      </template>
      <el-table
        row-key="uuid"
        :data="selectedProcessOrder"
        default-expand-all
        height="100%"
        width="100%"
        :tree-props="{ children: 'assignedWorkOrders' }"
      >
        <el-table-column
          prop="processName"
          label="工艺"
          align="center"
          width="140"
          show-overflow-tooltip
        />
        <el-table-column
          prop="showBillNumber"
          label="工单"
          align="center"
          min-width="140"
          show-overflow-tooltip
        >
          <template #default="scoped">{{ scoped.row.showBillNumber }}</template>
        </el-table-column>
        <el-table-column prop="projectCaseMo" label="时间周期" align="center" width="240">
          <template #default="scoped">
            <span>{{ scoped.row.startTime || '-' }}至{{ scoped.row.endTime || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="单件标工" align="center" width="160">
          <template #default="scoped">
            {{ scoped.row.processingTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="billNumber" label="小组" align="center" width="140">
          <template #default="scoped">
            <span>{{ scoped.row.workGroupName || '-' }}</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeVerify" v-loading="loading">返回修改</el-button>
          <el-button type="primary" @click="submitForm" v-loading="loading">确认提交</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 抽屉结束 -->
    <el-dialog
      v-model="openUnSelect"
      title="选择工单"
      width="500"
      append-to-body
      @close="closeSelect"
    >
      <el-checkbox-group v-model="checkList" v-if="!!formData.unallocatedWorkOrder.length">
        <el-checkbox
          :label="item.showBillNumber"
          :value="item.id"
          v-for="(item, index) in formData.unallocatedWorkOrder"
          :key="index"
        />
      </el-checkbox-group>
      <span v-else>无未分配订单</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmSelect">确认</el-button>
          <el-button @click="closeSelect">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { nextTick } from 'vue';
import Api from '@/api/index';
import dayjs from 'dayjs';
import func from '@/utils/func';
import { deepClone } from '@/utils/util';

const { proxy } = getCurrentInstance();
const emit = defineEmits(['confirm']);
const pageData = reactive({
  loading: false,
  open: false,
  formData: {},
  rules: {
    hours: [{ required: true, message: '请输入默认工时', trigger: 'blur' }],
    completionTime: [{ required: true, message: '请选择时间', trigger: 'blur' }],
    splitAmount: [{ required: true, message: '请输入数量', trigger: 'blur' }],
    splitAmount1: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  },
  unselectOptions: [],
  openVerify: false,
  openUnSelect: false,
  selectRow: {},
  checkList: [],
});

const {
  loading,
  open,
  formData,
  rules,
  unselectOptions,
  openVerify,
  openUnSelect,
  selectRow,
  checkList,
} = toRefs(pageData);

const selectedProcessOrder = computed(() => {
  if (Array.isArray(formData.value.selectedProcessOrder)) {
    const data = formData.value.selectedProcessOrder
      .map(item => {
        const { assignedWorkOrders } = item;
        if (Array.isArray(assignedWorkOrders) && assignedWorkOrders.length > 1) {
          assignedWorkOrders.forEach((assignedWorkOrder, assignedWorkOrderIndex) => {
            if (assignedWorkOrder.isVirtual) {
              assignedWorkOrder.isShow = false;
              item.virtual = deepClone(assignedWorkOrder);
              assignedWorkOrders.splice(assignedWorkOrderIndex, 1);
            } else {
              assignedWorkOrder.isShow = true;
            }
          });
        } else if (Array.isArray(assignedWorkOrders) && !assignedWorkOrders.length) {
          // item.virtual = null;
          if (item !== null && item.virtual !== undefined) {
            console.log('item.virtual', item.virtual);
            item.virtual.isShow = true;
            assignedWorkOrders.unshift(deepClone(item.virtual));
            item.virtual = null;
          }
        }
        return item;
      })
      .filter(item => item.checked);
    return data;
  }
  return [];
});

const lastTime = computed(() => {
  return selectedProcessOrder.value.reduce((max, item) => {
    const itemMaxTime = dayjs(item.startTime).isAfter(dayjs(item.endTime))
      ? item.startTime
      : item.endTime;
    return dayjs(itemMaxTime).isAfter(dayjs(max)) ? itemMaxTime : max;
  }, selectedProcessOrder.value[0]?.startTime || selectedProcessOrder.value[0]?.endTime);
});

// 获取详情
const getInfo = async ({ scheduleId }) => {
  try {
    loading.value = true;
    const param = {
      scheduleId,
    };
    const res = await Api.mps.mo.getSelectMoSplitItemV2(param);
    const { code, data } = res.data;
    if (code === 200) {
      formData.value = data;
      formData.value.completionTime = dayjs().format('YYYY-MM-DD');
      formData.value.selectedProcessOrder.forEach(processOrder => {
        processOrder.uuid = func.generateUUID();
        processOrder.isVirtual = true;
        const workItem = Array.isArray(processOrder?.workGroups)
          ? processOrder?.workGroups.find(item => item.workGroupCode === processOrder.workGroupCode)
          : '';
        if (!workItem && processOrder?.workGroupName && processOrder?.workGroupCode) {
          processOrder.workGroups.push({
            workGroupName: processOrder.workGroupName,
            workGroupCode: processOrder.workGroupCode,
          });
        }
        processOrder.assignedWorkOrders.forEach(item => {
          if (!item.id) {
            processOrder.processingTime =
              item.processingTime < 0 ? 1 : proxy.secondToHour2(item.processingTime || 0);
            processOrder.billNumber = item.billNumber;
            processOrder.showBillNumber = item.showBillNumber;
            item.isVirtual = true;
          }
          item.isChild = true;
          item.startTime = processOrder.startTime;
          item.endTime = processOrder.endTime;
          item.workGroupName = processOrder.workGroupName;
          item.workGroupCode = processOrder.workGroupCode;
          item.processingTime =
            item.processingTime <= 0 ? 1 : proxy.secondToHour2(item.processingTime);
          item.uuid = func.generateUUID();
        });
      });
      if (Array.isArray(formData.value.unallocatedWorkOrder)) {
        formData.value.unallocatedWorkOrder.forEach(item => (item.isChild = true));
      }
    }
    loading.value = false;
  } catch (err) {
    loading.value = false;
  }
};

// 处理工艺变化
const handleSelectedProcessOrder = item => {
  if (item.checked) return;
  item.assignedWorkOrders.forEach((moItem, index) => {
    if (!moItem.isVirtual) {
      // 不是虚拟mo
      formData.value.unallocatedWorkOrder.push(moItem);
      item.assignedWorkOrders.splice(index, 1);
    }
  });
};

// 处理日期变化
const handleDateChange = (daterange, row) => {
  row.assignedWorkOrders.forEach(item => {
    item.startTime = daterange ? daterange.startDate : null;
    item.endTime = daterange ? daterange.endDate : null;
  });
};

const handleGroupChange = row => {
  let workGroup = row.workGroups.find(item => item.workGroupCode === row.workGroupCode);
  row.workGroupName = workGroup?.workGroupName || null;
  row.assignedWorkOrders.forEach(item => {
    item.workGroupName = workGroup?.workGroupName || null;
    item.workGroupCode = workGroup?.workGroupCode || null;
  });
  if (row.processCode === '1851181118047055877' || row.processCode === '1851181118047055876') {
    let processOrder;
    switch (row.processCode) {
      case '1851181118047055877':
        processOrder = selectedProcessOrder.value.find(
          item => item.processCode === '1851181118047055876'
        );
        processOrder.workGroupName = workGroup?.workGroupName;
        processOrder.workGroupCode = workGroup?.workGroupCode;
        processOrder.assignedWorkOrders.forEach(item => {
          item.workGroupName = workGroup?.workGroupName || null;
          item.workGroupCode = workGroup?.workGroupCode || null;
        });
        break;
      case '1851181118047055876':
        processOrder = selectedProcessOrder.value.find(
          item => item.processCode === '1851181118047055877'
        );
        processOrder.workGroupName = workGroup?.workGroupName;
        processOrder.workGroupCode = workGroup?.workGroupCode;
        processOrder.assignedWorkOrders.forEach(item => {
          item.workGroupName = workGroup?.workGroupName || null;
          item.workGroupCode = workGroup?.workGroupCode || null;
        });
        break;
    }
  }
};

// 移除子项
const removeRow = row => {
  formData.value.selectedProcessOrder.forEach(processOrder => {
    for (let i = processOrder.assignedWorkOrders.length - 1; i >= 0; i--) {
      if (processOrder.assignedWorkOrders[i].id === row.id) {
        processOrder.assignedWorkOrders.splice(i, 1);
      }
    }
  });
  formData.value.unallocatedWorkOrder.push(row);
};

// 处理校验
const handleVerify = () => {
  const unTimesLen = formData.value.selectedProcessOrder.filter(
    item => (!item.startTime || !item.endTime) && item.checked
  ).length;
  if (unTimesLen > 0)
    return proxy.$message({
      type: 'warning',
      message: '请选择时间周期',
    });
  if (formData.value.unallocatedWorkOrder.length > 0)
    return proxy.$message({
      type: 'warning',
      message: '任有未分配工单',
    });
  if (!formData.value.splitAmount && formData.value.splitAmount !== 0)
    return proxy.$message({
      type: 'warning',
      message: '拆分数量不能为空',
    });

  proxy.$refs['submitFormRef'].validate(async valid => {
    if (valid) {
      openVerify.value = true;
    }
  });
};

// 关闭校验弹窗
const closeVerify = () => {
  openVerify.value = false;
};

// 添加子项
const addChildren = row => {
  selectRow.value = row;
  openUnSelect.value = true;
};

// 关闭未选中弹窗
const closeSelect = () => {
  openUnSelect.value = false;
  checkList.value = [];
  selectRow.value = {};
};

// 确认选择
const confirmSelect = () => {
  openUnSelect.value = false;

  checkList.value.forEach(id => {
    const moItem = formData.value.unallocatedWorkOrder.find(item => item.id === id);
    moItem.processingTime = proxy.secondToHour2(moItem.processingTime);
    selectRow.value.assignedWorkOrders.push({
      ...moItem,
      startTime: selectRow.value.startTime,
      endTime: selectRow.value.endTime,
      workGroupCode: selectRow.value.workGroupCode,
      workGroupName: selectRow.value.workGroupName,
    });
  });
  checkList.value.forEach(id => {
    const findIndex = formData.value.unallocatedWorkOrder.findIndex(item => item.id === id);
    formData.value.unallocatedWorkOrder.splice(findIndex, 1);
  });
  checkList.value = [];
  selectRow.value = {};
};

// 弹出框提交表单
const submitForm = () => {
  const unTimesLen = formData.value.selectedProcessOrder.filter(
    item => (!item.startTime || !item.endTime) && item.checked
  ).length;
  if (unTimesLen > 0)
    return proxy.$message({
      type: 'warning',
      message: '请选择时间周期',
    });
  if (formData.value.unallocatedWorkOrder.length > 0)
    return proxy.$message({
      type: 'warning',
      message: '任有未分配工单',
    });
  if (!formData.value.splitAmount && formData.value.splitAmount !== 0)
    return proxy.$message({
      type: 'warning',
      message: '拆分数量不能为空',
    });
  const form = deepClone(formData.value);

  form.selectedProcessOrder.forEach(processOrder => {
    if (processOrder.virtual) processOrder.assignedWorkOrders.unshift(processOrder.virtual);
    processOrder.assignedWorkOrders = processOrder.assignedWorkOrders.map(item => {
      if (item.id <= 0 || item.id === null) {
        processOrder.processingTime = proxy.hourTosecond(item.processingTime);
        processOrder.startTime = processOrder.startTime;
        processOrder.endTime = processOrder.endTime;
      }
      return {
        ...item,
        processingTime: proxy.hourTosecond(item.processingTime),
      };
    });
  });
  proxy.$refs['submitFormRef'].validate(async valid => {
    if (valid) {
      try {
        loading.value = true;
        const res = await Api.mps.mo.updatemMoSplitItem(form);
        const { code, msg, data } = res.data;
        if (code === 200) {
          emit('confirm', data);
          closeDrawer();
          closeVerify();
          proxy.$message.success(msg);
        }
        loading.value = false;
      } catch (error) {
        loading.value = false;
      }
    }
  });
};

// 打开抽屉
const openDrawer = task => {
  getInfo(task);
  open.value = true;
};

// 关闭抽屉
const closeDrawer = () => {
  open.value = false;
  nextTick(() => {
    unselectOptions.value = [];
    formData.value = {
      selectedProcessOrder: [],
    };
    proxy.resetForm('submitFormRef');
  });
};

defineExpose({
  openDrawer,
});
</script>
<style lang="scss">
@use '@/styles/masterDrawer';
</style>
<style scoped lang="scss">
.warn-text {
  color: red;
  font-size: 22px;
  font-weight: 600;
}
</style>
